<template>
  <div class="dashboard">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <el-card class="welcome-card">
        <div class="welcome-content">
          <div class="welcome-text">
            <h2>欢迎回来，{{ currentUser?.realName || currentUser?.username }}！</h2>
            <p>今天是 {{ currentDate }}，祝您工作愉快</p>
          </div>
          <div class="welcome-avatar">
            <el-avatar 
              :size="60" 
              :src="currentUser?.avatar"
              :icon="UserFilled"
            />
          </div>
        </div>
      </el-card>
    </div>

    <!-- 统计数据 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <el-card class="stats-card">
            <div class="stats-item">
              <div class="stats-icon books">
                <el-icon><Reading /></el-icon>
              </div>
              <div class="stats-content">
                <div class="stats-number">{{ stats.totalBooks }}</div>
                <div class="stats-label">图书总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <el-card class="stats-card">
            <div class="stats-item">
              <div class="stats-icon authors">
                <el-icon><User /></el-icon>
              </div>
              <div class="stats-content">
                <div class="stats-number">{{ stats.totalAuthors }}</div>
                <div class="stats-label">作者总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <el-card class="stats-card">
            <div class="stats-item">
              <div class="stats-icon borrows">
                <el-icon><DocumentCopy /></el-icon>
              </div>
              <div class="stats-content">
                <div class="stats-number">{{ stats.totalBorrows }}</div>
                <div class="stats-label">借阅记录</div>
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="12" :sm="6" :md="6" :lg="6" :xl="6">
          <el-card class="stats-card">
            <div class="stats-item">
              <div class="stats-icon users">
                <el-icon><UserFilled /></el-icon>
              </div>
              <div class="stats-content">
                <div class="stats-number">{{ stats.totalUsers }}</div>
                <div class="stats-label">用户总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 功能模块 -->
    <div class="modules-section">
      <h3 class="section-title">功能模块</h3>
      <el-row :gutter="20">
        <el-col 
          v-for="module in modules" 
          :key="module.name"
          :xs="12" 
          :sm="8" 
          :md="6" 
          :lg="4" 
          :xl="3"
        >
          <el-card 
            class="module-card" 
            :class="{ disabled: !module.enabled }"
            @click="handleModuleClick(module)"
          >
            <div class="module-content">
              <div class="module-icon" :style="{ color: module.color }">
                <el-icon :size="32">
                  <component :is="module.icon" />
                </el-icon>
              </div>
              <div class="module-info">
                <h4 class="module-name">{{ module.title }}</h4>
                <p class="module-desc">{{ module.description }}</p>
                <div class="module-status">
                  <el-tag 
                    :type="module.enabled ? 'success' : 'info'" 
                    size="small"
                  >
                    {{ module.enabled ? '已启用' : '开发中' }}
                  </el-tag>
                </div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 最近操作 -->
    <div class="recent-section">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-card class="recent-card">
            <template #header>
              <div class="card-header">
                <span>最近添加的图书</span>
                <el-button type="text" @click="$router.push('/book')">查看更多</el-button>
              </div>
            </template>
            <div class="recent-list">
              <div 
                v-for="book in recentBooks" 
                :key="book.id"
                class="recent-item"
              >
                <div class="item-info">
                  <div class="item-title">{{ book.title }}</div>
                  <div class="item-meta">{{ book.author }} · {{ formatDate(book.createTime) }}</div>
                </div>
                <el-tag size="small" :type="book.status === 1 ? 'success' : 'danger'">
                  {{ book.status === 1 ? '上架' : '下架' }}
                </el-tag>
              </div>
              <div v-if="recentBooks.length === 0" class="empty-state">
                暂无数据
              </div>
            </div>
          </el-card>
        </el-col>
        
        <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
          <el-card class="recent-card">
            <template #header>
              <div class="card-header">
                <span>最近操作日志</span>
                <el-button type="text" @click="$router.push('/log')">查看更多</el-button>
              </div>
            </template>
            <div class="recent-list">
              <div 
                v-for="log in recentLogs" 
                :key="log.id"
                class="recent-item"
              >
                <div class="item-info">
                  <div class="item-title">{{ log.operation }}</div>
                  <div class="item-meta">{{ log.username }} · {{ formatDateTime(log.createTime) }}</div>
                </div>
                <el-tag size="small" :type="getLogTypeTag(log.type)">
                  {{ log.type }}
                </el-tag>
              </div>
              <div v-if="recentLogs.length === 0" class="empty-state">
                暂无数据
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  UserFilled, 
  User, 
  Reading, 
  DocumentCopy, 
  Management,
  OfficeBuilding,
  Collection,
  DataBoard,
  Setting,
  Document
} from '@element-plus/icons-vue'
import { getUser } from '@/utils/auth'
import statsApi from '@/api/stats'
import bookApi from '@/api/book'
import logApi from '@/api/log'

const router = useRouter()

// 当前用户信息
const currentUser = computed(() => getUser())

// 当前日期
const currentDate = computed(() => {
  return new Date().toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    weekday: 'long'
  })
})

// 统计数据
const stats = reactive({
  totalBooks: 0,
  totalAuthors: 0,
  totalBorrows: 0,
  totalUsers: 0
})

// 功能模块配置
const modules = ref([
  {
    name: 'author',
    title: '作者管理',
    description: '管理图书作者信息',
    icon: 'User',
    color: '#409eff',
    enabled: true,
    route: '/author'
  },
  {
    name: 'book',
    title: '图书管理',
    description: '管理图书信息和库存',
    icon: 'Reading',
    color: '#67c23a',
    enabled: true,
    route: '/book'
  },
  {
    name: 'category',
    title: '分类管理',
    description: '管理图书分类信息',
    icon: 'Collection',
    color: '#e6a23c',
    enabled: true,
    route: '/category'
  },
  {
    name: 'publisher',
    title: '出版社管理',
    description: '管理出版社信息',
    icon: 'OfficeBuilding',
    color: '#f56c6c',
    enabled: true,
    route: '/publisher'
  },
  {
    name: 'borrow',
    title: '借阅管理',
    description: '管理图书借阅记录',
    icon: 'DocumentCopy',
    color: '#909399',
    enabled: true,
    route: '/borrow'
  },
  {
    name: 'user',
    title: '用户管理',
    description: '管理系统用户',
    icon: 'UserFilled',
    color: '#606266',
    enabled: true,
    route: '/user'
  },
  {
    name: 'log',
    title: '操作日志',
    description: '查看系统操作记录',
    icon: 'Document',
    color: '#303133',
    enabled: true,
    route: '/log'
  },
  {
    name: 'setting',
    title: '系统设置',
    description: '系统配置和参数',
    icon: 'Setting',
    color: '#909399',
    enabled: false,
    route: '/setting'
  }
])

// 最近图书数据
const recentBooks = ref([])

// 最近日志数据
const recentLogs = ref([])

// 处理模块点击
const handleModuleClick = (module) => {
  if (!module.enabled) {
    ElMessage.info(`${module.title}功能正在开发中，敬请期待！`)
    return
  }
  
  router.push(module.route)
}

// 获取日志类型标签
const getLogTypeTag = (type) => {
  const typeMap = {
    '新增': 'success',
    '修改': 'warning',
    '删除': 'danger',
    '查询': 'info',
    '登录': 'success',
    '退出': 'info'
  }
  return typeMap[type] || 'info'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString('zh-CN')
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return '-'
  return new Date(datetime).toLocaleString('zh-CN')
}

// 获取统计数据
const getStats = async () => {
  try {
    // 调用统计API获取真实数据
    const [bookStats, authorStats, borrowStats, userStats] = await Promise.all([
      bookApi.getList({ pageNo: 1, pageSize: 1 }),
      // 这里需要后端提供统计接口，暂时用列表接口的total字段
      statsApi.getAuthorStats().catch(() => ({ total: 0 })),
      borrowApi.getList({ pageNo: 1, pageSize: 1 }),
      statsApi.getUserStats().catch(() => ({ total: 0 }))
    ])
    
    stats.totalBooks = bookStats?.total || 0
    stats.totalAuthors = authorStats?.total || 0
    stats.totalBorrows = borrowStats?.total || 0
    stats.totalUsers = userStats?.total || 0
  } catch (error) {
    console.error('获取统计数据失败:', error)
    // 如果API调用失败，设置默认值
    stats.totalBooks = 0
    stats.totalAuthors = 0
    stats.totalBorrows = 0
    stats.totalUsers = 0
  }
}

// 获取最近图书
const getRecentBooks = async () => {
  try {
    // 调用真实的图书列表API获取最近添加的图书
    const result = await bookApi.getList({ 
      pageNo: 1, 
      pageSize: 5,
      orderBy: 'createTime',
      orderDirection: 'desc'
    })
    
    if (result && result.result) {
      recentBooks.value = result.result.map(book => ({
        id: book.id,
        title: book.title,
        author: book.authorName || book.author || '未知作者',
        status: book.status,
        createTime: book.createTime
      }))
    }
  } catch (error) {
    console.error('获取最近图书失败:', error)
    recentBooks.value = []
  }
}

// 获取最近日志
const getRecentLogs = async () => {
  try {
    // 调用真实的日志API获取最近操作记录
    const result = await logApi.getList({ 
      pageNo: 1, 
      pageSize: 5,
      orderBy: 'createTime',
      orderDirection: 'desc'
    })
    
    if (result && result.result) {
      recentLogs.value = result.result.map(log => ({
        id: log.id,
        operation: log.operation || log.description || '未知操作',
        username: log.username || log.operatorName || '系统',
        type: log.type || log.operationType || '操作',
        createTime: log.createTime
      }))
    }
  } catch (error) {
    console.error('获取最近日志失败:', error)
    recentLogs.value = []
  }
}

// 组件挂载时获取数据
onMounted(() => {
  getStats()
  getRecentBooks()
  getRecentLogs()
})
</script>

<style scoped>
.dashboard {
  padding: 20px;
}

.welcome-section {
  margin-bottom: 20px;
}

.welcome-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.welcome-card :deep(.el-card__body) {
  padding: 30px;
}

.welcome-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.welcome-text h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
}

.welcome-text p {
  margin: 0;
  opacity: 0.9;
  font-size: 14px;
}

.stats-section {
  margin-bottom: 30px;
}

.stats-card {
  height: 100px;
  cursor: pointer;
  transition: all 0.3s;
}

.stats-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.stats-item {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
}

.stats-icon.books {
  background: rgba(103, 194, 58, 0.1);
  color: #67c23a;
}

.stats-icon.authors {
  background: rgba(64, 158, 255, 0.1);
  color: #409eff;
}

.stats-icon.borrows {
  background: rgba(230, 162, 60, 0.1);
  color: #e6a23c;
}

.stats-icon.users {
  background: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
}

.stats-content {
  flex: 1;
}

.stats-number {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stats-label {
  font-size: 14px;
  color: #909399;
}

.modules-section {
  margin-bottom: 30px;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.module-card {
  height: 140px;
  cursor: pointer;
  transition: all 0.3s;
  margin-bottom: 20px;
}

.module-card:hover:not(.disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.module-card.disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.module-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  text-align: center;
  height: 100%;
  padding: 10px;
}

.module-icon {
  margin-bottom: 12px;
}

.module-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.module-name {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.module-desc {
  margin: 0 0 8px 0;
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

.module-status {
  margin-top: auto;
}

.recent-section {
  margin-bottom: 20px;
}

.recent-card {
  height: 300px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.recent-list {
  height: 220px;
  overflow-y: auto;
}

.recent-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f0f0f0;
}

.recent-item:last-child {
  border-bottom: none;
}

.item-info {
  flex: 1;
}

.item-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.item-meta {
  font-size: 12px;
  color: #909399;
}

.empty-state {
  text-align: center;
  color: #909399;
  font-size: 14px;
  padding: 40px 0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard {
    padding: 10px;
  }
  
  .welcome-content {
    flex-direction: column;
    text-align: center;
  }
  
  .welcome-avatar {
    margin-top: 16px;
  }
  
  .stats-number {
    font-size: 24px;
  }
  
  .module-card {
    height: 120px;
  }
  
  .module-name {
    font-size: 14px;
  }
  
  .module-desc {
    font-size: 11px;
  }
}
</style>
